package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
//@WebFilter("/*")
@Slf4j
public class TextFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转Http
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取路径
        String path = request.getServletPath();
        //登录,放行
        if(path.contains("login")){
            log.info("登录 {}",path );
            filterChain.doFilter(request,response);
            return;
        }
        //不是登录, 验证token
        String token = request.getHeader("token");
        if(token == null|| token.isEmpty()){
            log.info("token为空:{}",path);
            response.setStatus(401);
            return;
        }
        //token为空,error
        try {
            JwtUtils.parseToken(token);
        }
        catch (Exception e) {
            log.info("token解析失败:{}",e.getMessage());
            response.setStatus(401);
            return;
        }
        //token非空,解析+校验
        filterChain.doFilter(request,response);
        log.info("删除:{}",path);
        CurrentUserHoler.removeCurrentUser();
        //放行
    }
}
